import axios from 'axios'
import { Modal } from 'ant-design-vue'
import utils from 'xe-utils'

let version: string = ''
let isConfirming = false

interface VersionDto {
  version: string
}

const onCheckUpdate = utils.debounce(() => {
  checkUpdate()
}, 4000)

function checkUpdate() {
  axios<VersionDto>({
    url: location.origin + '/version.json',
  }).then(({ data }) => {
    if (!version) {
      version = data.version
    } else if (version != data.version) {
      if (isConfirming) return
      isConfirming = true
      Modal.confirm({
        title: '提示',
        type: 'info',
        content: '发现新版本, 是否更新?',
        onOk() {
          location.reload()
          isConfirming = false
        },
        onCancel() {
          isConfirming = false
        },
      })
    }
  })
}

export function startCheckUpdate() {
  onCheckUpdate()
  window.addEventListener('focus', () => {
    onCheckUpdate()
  })
  document.addEventListener('visibilitychange', () => {
    onCheckUpdate()
  })

  window.addEventListener('error', (e: any) => {
    if (e.target && e.target.tagName?.toLowerCase() === 'script') {
      onCheckUpdate()
    }
  })
}
